import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import type { Component } from 'vue'
import LoginView from '../views/LoginView.vue'
import MainView from '@/views/MainView.vue'
import HomeView from '@/views/HomeView.vue'
import UserView from '@/views/UserView.vue'
import RoleView from '@/views/RoleView.vue'
import MenuView from '@/views/MenuView.vue'
import DepartmentView from '@/views/DepartmentView.vue'
import WarehouseView from '@/views/WarehouseView.vue'
import { getUserInfo } from '@/api'
import { getDynamicRouterAsync } from '@/api'

// 动态路由映射 - 使用正确的组件类型
const dynamicRouteMap: Record<string, Component> = {
  WarehouseView: WarehouseView,
  UserView: UserView,
  RoleView: RoleView,
  MenuView: MenuView,
  DepartmentView: DepartmentView,
  // 可以在这里添加更多动态路由组件映射
}

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login',
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
    },
    {
      path: '/main',
      name: 'main',
      component: MainView,
      redirect: '/main/home', // 主页面默认重定向到首页
      children: [
        {
          path: 'home',
          name: 'home',
          component: HomeView,
        },
        // 动态路由将在这里添加
      ],
    },
  ],
})

// 动态添加路由的方法
export const addDynamicRoutes = (menus: unknown[]) => {
  const processMenu = (menu: unknown) => {
    const menuData = menu as {
      path?: string
      component?: string
      code?: string
      children?: unknown[]
    }

    // 处理当前菜单的路由
    if (menuData.path && menuData.component && dynamicRouteMap[menuData.component]) {
      // 检查路径是否以/main/开头（二级菜单）
      if (menuData.path.startsWith('/main/')) {
        const childRoute = {
          path: menuData.path.replace('/main/', ''),
          name: menuData.code || undefined,
          component: dynamicRouteMap[menuData.component],
        } as RouteRecordRaw

        // 检查路由是否已存在
        const existingChildRoute = router.getRoutes().find((r) => r.path === childRoute.path)
        if (!existingChildRoute) {
          router.addRoute('main', childRoute)
          console.log('动态添加路由:', childRoute)
        }
      }
    }

    // 递归处理子菜单
    if (menuData.children && Array.isArray(menuData.children)) {
      menuData.children.forEach(processMenu)
    }
  }

  menus.forEach(processMenu)
}

// 标记是否已经添加过动态路由
let dynamicRoutesAdded = false

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  // 检查用户是否已登录
  const userInfo = getUserInfo()

  // 如果用户已登录且访问的是主页面相关路由，但动态路由还未添加
  if (userInfo && to.path.startsWith('/main') && !dynamicRoutesAdded) {
    try {
      // 获取动态菜单
      const menuResponse = await getDynamicRouterAsync({ userId: userInfo.id || 1 })
      if (menuResponse.success && menuResponse.data && Array.isArray(menuResponse.data)) {
        addDynamicRoutes(menuResponse.data)
        dynamicRoutesAdded = true

        // 重新导航到当前路由，确保动态路由生效
        next({ ...to, replace: true })
        return
      }
    } catch (error) {
      console.error('获取动态菜单失败:', error)
    }
  }

  next()
})

export default router
